package com.bookstore.controller;

import com.bookstore.common.Result;
import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@Api(tags = "用户管理接口")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result<Boolean> register(@RequestBody User user) {
        return Result.success(userService.register(user));
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<User> login(
            @ApiParam("用户名") @RequestParam String username,
            @ApiParam("密码") @RequestParam String password) {
        User user = userService.login(username, password);
        if (user == null) {
            return Result.error(401, "用户名或密码错误");
        }
        // 清除密码
        user.setPassword(null);
        return Result.success(user);
    }

    @PutMapping("/{id}/password")
    @ApiOperation("修改密码")
    public Result<Boolean> changePassword(
            @ApiParam("用户ID") @PathVariable Integer id,
            @ApiParam("旧密码") @RequestParam String oldPassword,
            @ApiParam("新密码") @RequestParam String newPassword) {
        return Result.success(userService.changePassword(id, oldPassword, newPassword));
    }

    @PutMapping("/{id}")
    @ApiOperation("更新用户信息")
    public Result<Boolean> updateUserInfo(
            @ApiParam("用户ID") @PathVariable Integer id,
            @RequestBody User user) {
        user.setUserId(id);
        return Result.success(userService.updateUserInfo(user));
    }

    @GetMapping("/{id}")
    @ApiOperation("获取用户信息")
    public Result<User> getUserInfo(@ApiParam("用户ID") @PathVariable Integer id) {
        User user = userService.getById(id);
        if (user != null) {
            user.setPassword(null);
        }
        return Result.success(user);
    }
} 